package com.atguigu.config;

import com.alibaba.dubbo.config.annotation.Reference;
import com.atguigu.entity.Admin;
import com.atguigu.entity.Permission;
import com.atguigu.service.AdminService;
import com.atguigu.service.PermissionService;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author: 翟文海
 * @Date: 2022/11/5/005 15:37
 * @Version: 1.0
 * @Description:
 **/
@Component
public class UserDetailsServiceImpl implements UserDetailsService {
    @Reference
    private AdminService adminService;
    @Reference
    private PermissionService permissionService;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        Admin admin = adminService.getByUsername(s);
        if (admin == null) {
            throw new UsernameNotFoundException(s);
        }else {
            //TODO 授权
            List<GrantedAuthority> grantedAuthorities = new ArrayList<>();
            List<Permission> permissionList = permissionService.findPermissionListByAdminId(admin.getId());
            permissionList.stream()
                    .forEach(permission -> {
                        if (!StringUtils.isEmpty(permission.getCode())) {
                            grantedAuthorities.add(new SimpleGrantedAuthority(permission.getCode()));
                        }
                    });

            User user = new User(admin.getUsername(), admin.getPassword(), grantedAuthorities);
            return user;
        }
    }
}
